﻿using PwjCy.Lite.Common;
using PwjCy.Lite.Core;
using PwjCy.Lite.Persistence;
using PwjCy.Lite.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace PwjCy.Lite.EntityLite.Imp
{
    /// <summary>
    /// PwjCyObject映射对象
    /// </summary>
    public sealed class EntityLiteRelationMap
    {
        /// <summary>
        /// 私有构造函数
        /// </summary>
        private EntityLiteRelationMap() { }

        private static readonly Lazy<EntityLiteRelationMap> lazy = new Lazy<EntityLiteRelationMap>(() => new EntityLiteRelationMap());
        /// <summary>
        /// EntityLiteMapObjcet单例对象
        /// </summary>
        public static EntityLiteRelationMap Instance { get { return lazy.Value; } }
        /// <summary>
        /// Sql搭建器
        /// </summary>
        /// <param name="storageAlias"></param>
        /// <returns></returns>
        public ISqlBuilder SqlBuilder(string storageAlias)
        {
            return PLServices.PersisterMapping.GetDirver<IPersistenceDriver>(storageAlias).SqlBuilder;
        }
        /// <summary>
        /// 数据库连接
        /// </summary>
        /// <param name="storageAlias"></param>
        /// <returns></returns>
        public IConnection Connection(string storageAlias)
        {
            return PLServices.PersisterMapping.GetDirver<IDriver>(storageAlias)
                .GetConnection(PLServices.PersisterMapping.GetDirver<IStorageContext>(storageAlias));
        }
        /// <summary>
        /// DAO对象类型描述
        /// </summary>
        /// <param name="pwjcyOjbect"></param>
        /// <returns></returns>
        public IPwjCyOjbectTypeDescription PwjCyOjbectTypeDescription(IPwjCyObject pwjcyOjbect)
        {
            return new PwjCyOjbectTypeDescription(pwjcyOjbect.GetType());
        }
        public IPwjCyOjbectTypeDescription PwjCyOjbectTypeDescription(Type pwjcyObjectType)
        {
            return new PwjCyOjbectTypeDescription(pwjcyObjectType);
        }

        /// <summary>
        /// 设置参数值
        /// </summary>
        /// <param name="stmt"></param>
        /// <param name="pwjcyObject"></param>
        public void SetParamValue(IPreparedStatement stmt, IPwjCyObject pwjcyObject)
        {
            foreach (var pro in this.PwjCyOjbectTypeDescription(pwjcyObject).PwjCyFields)
            {
                stmt.SetParameter(pro.Name, pro.GetValue(pwjcyObject, null));
            }
        }
    }
}
